package cn.com.xj.plat.controller;

import cn.com.xj.common.param.out.ServiceResp;
import cn.com.xj.plat.model.SessionLoginUser;
import cn.com.xj.plat.service.MenuService;
import cn.com.xj.plat.util.LoginUtils;
import com.netflix.discovery.converters.Auto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController{

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Value("${spring.cloud.user.staff.uri:}")
    private String staffUri;

    @Value("${security.client.id:}")
    private String securityClientId;

    @Value("${security.client.secret:}")
    private String securityClientSecret;

    @Autowired
    private MenuService menuService;
    
    @RequestMapping("/")
    public String index(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
        try {
        	if(LoginUtils.isLogin(request.getSession())){
        		return "redirect:/home";
        	}else{
        		return "redirect:/login/index";
        	}
        }catch(Exception e){
        	e.printStackTrace();
        }
        return "redirect:/login/index";
    }

    /** 登录后跳转至首页 */
    @RequestMapping("/home")
    public String home(Model model,HttpServletRequest request,HttpSession session) {
        try {
            /** 读取当前登陆用户的权限 */
            SessionLoginUser loginUser = LoginUtils.getLoginUser(session);
            model.addAttribute("loginName",loginUser.getLoginName());
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("platUserId",loginUser.getId());
            param.put("isMenu",1);
            ServiceResp<Object> resp = menuService.queryPlatUserMenu(param);
            List<Map<String,Object>> menus = (List<Map<String,Object>>)resp.getBody();
            model.addAttribute("menus",menus);
        } catch (Exception e) {
            e.printStackTrace();
            return "/home/mainFrame";
        }
        return "/home/mainFrame";
    }

    public Map<String,Object> getFirstMenu(Map<String,Object> map){
        Map<String,Object> firstMenu = map;
        if (map.get("children")!=null){
            List<Map<String,Object>> firstMenuChildren1 = (List<Map<String,Object>>)map.get("children");
            if (firstMenuChildren1.size()>0){
                firstMenu = firstMenuChildren1.get(0);
                firstMenu=getFirstMenu(firstMenu);
            }
        }
        return firstMenu;
    }

    @RequestMapping("/home/leftMenuTree")
    private String leftMenuTree(Model model,HttpServletRequest request) {
        Map<String, Object> param = new HashMap<String, Object>();
        try {

        } catch (Exception e) {
            e.printStackTrace();
            return "/home/leftMenuTree";
        }
        return "/home/leftMenuTree";
    }

    /**iframe高度代理*/
    @RequestMapping("/agent")
    private String agent() {
        return "/home/agent";
    }

    /**公共错误页面(在iframe中显示)*/
    @RequestMapping("/toerror")
    private String error() {
        return "/common/error";
    }





//    @RequestMapping("/index")
//    private String index(Model model,HttpServletRequest request) {
//        try {
//            model.addAttribute("staticFilepath",staticFilepath);
//            /** 读取当前登陆用户的权限 */
//            StaffBean staffInfo = LoginUtil.getLoginStaffInfo(request);
//            System.out.println(">>>>>>>>>>>>>>>>当前登录登录用户名称："+staffInfo.getStaffName()+":"+staffInfo.getId()+"<<<<<<<<<<<<<<<");
////                System.out.println("所属用户组："+staffInfo.getGroupId());
////                System.out.println("所属角色："+staffInfo.getRoleInfoList().get(0).getRoleName());
//            model.addAttribute("staffName",staffInfo.getStaffName());
//            //根据用户staff信息查出相应的角色 角色绑定了菜单
//            Map<String, Object> param = new HashMap<String, Object>();
//            param.put("staffId",staffInfo.getId());
//            String isSuperManager = staffInfo.getIsSuperManager();
////            System.out.println("是否超级管理员："+isSuperManager);
//            if (isSuperManager!=null){
//                param.put("isSuperManager",isSuperManager);
//            }else {
//                param.put("isSuperManager",0);
//            }
//            ServerResp<Object> resp = menuInfoService.queryUserMenu(param);
//            List<Map<String,Object>> menus = (List<Map<String,Object>>)resp.getBody();
////            System.out.println("menus:"+menus);
//            model.addAttribute("menus",menus);
//            //*********web-controller获取系统参数的公共方法********************
//            String projectName=null;
////            List<String> valueList  = sysParmsDataService.getParmValues("projectName");
////            if (valueList!=null&&valueList.size()>0){
////                projectName = valueList.get(0);
////            }
//            if (StringUtils.isBlank(projectName)){
//                projectName="全渠道互联网运营中心云平台";
//            }
//            model.addAttribute("projectName",projectName);
//        }catch (Exception e){
//            e.printStackTrace();
//            model.addAttribute("errorMsg","系统异常");
//            return "/common/error";
//        }
//        return "index";
//    }

//    @RequestMapping("/toHome")
//    public String toHome(Model model,HttpServletRequest request,HttpServletResponse response) {
//        try {
//            String clientId = securityClientId;
//            String clientSecret = securityClientSecret;
//            String token = request.getParameter("token");
//            //通过token获取后台用户信息
////            NameValuePair[] postParams = new NameValuePair[]{
////                    new NameValuePair("clientId",clientId),
////                    new NameValuePair("clientSecret",clientSecret),
////                    new NameValuePair("token",token)};
////            String staffStr = HttpUtils.post(staffUri,postParams,"");
//            if(StringUtils.isBlank(staffStr)){
//                System.out.println("获取用户信息失败");
//                return "redirect:/login/index";
//            }
//            JSONObject staffObj = JSONObject.parseObject(staffStr);
//            String retCode =staffObj.getString("retCode");
//            if("0".equals(retCode)){
//                Map<String,Object> staffInfo = staffObj.getJSONObject("staffInfo");
//                if(staffInfo==null){
//                    System.out.println("获取用户信息失败:"+staffObj.getString("retMsg"));
//                    return "redirect:/login/index";
//                }
//                String loginTicket = TicketFlag.getTicket();
//                staffInfo.put("loginTicket",loginTicket);
//                loginService.saveStaffToRedis(staffInfo);
//                CookieUtil.setCookie(request,response,
//                        LoginUtil.LOGIN_COOKIE_KEY,loginTicket,3600); //将ticket放入cookie(秒)
//            }else{
//                return "redirect:/login/index";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "redirect:/login/index";
//        }
//        return "redirect:/home";
//    }

}

